import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import connect from "@/utils/mongodb";
import User from "@/model/User";
import bcrypt from "bcryptjs";
import { v4 as uuidv4 } from "uuid";
import { sendLoginNotification } from "@/services/emailService";
import requestIp from "request-ip";
import { UAParser } from "ua-parser-js"; // 关键修正：使用命名导出

// 利用request-ip库获取客户端IP
const getClientIp = (req) => {
  try {
    // 适配NextAuth的req格式（将req转为request-ip可识别的格式）
    const mockReq = {
      headers: {},
      connection: { remoteAddress: "未知IP" } // 兜底
    };

    // 复制headers到mockReq（处理不同格式的req）
    if (req?.headers?.get) {
      // 标准Request对象：遍历所有headers
      const headers = req.headers.entries();
      for (const [key, value] of headers) {
        mockReq.headers[key] = value;
      }
    } else if (req?.headers) {
      // 普通对象格式的headers
      mockReq.headers = { ...req.headers };
    }

    // 本地开发环境特殊处理
    if (process.env.NODE_ENV === "development") {
      return requestIp.getClientIp(mockReq) || "127.0.0.1";
    }

    // 生产环境使用库提取IP
    return requestIp.getClientIp(mockReq) || "未知IP";
  } catch (error) {
    console.error("获取IP失败:", error);
    return "未知IP";
  }
};



// 解析设备信息（浏览器、系统等）
const getDeviceInfo = (req) => {
  try {
    // 获取user-agent头
    let userAgent = "未知设备";
    if (req?.headers?.get) {
      // 标准Request对象
      userAgent = req.headers.get("user-agent") || userAgent;
    } else if (req?.headers) {
      // NextAuth的headers对象
      userAgent = req.headers["user-agent"] || userAgent;
    }

    // 解析user-agent（使用命名导出的UAParser）
    const parser = new UAParser(userAgent);
    const result = parser.getResult();

    // 格式化设备信息（例如："Chrome 126.0.0 / Windows 10"）
    return `${result.browser.name || "未知浏览器"} ${result.browser.version || ""} / ${result.os.name || "未知系统"} ${result.os.version || ""}`.trim();
  } catch (error) {
    console.error("解析设备信息失败:", error);
    return "未知设备";
  }
};

export const authOptions = {
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        email: { label: "Email", type: "email" },
        password: { label: "Password", type: "password" }
      },
      async authorize(credentials, req) {  // 注意：这里添加了 req 参数
        await connect();

        // 1. 查询用户（包含注册IP、上次登录等信息）
        const user = await User.findOne({ email: credentials.email });
        if (!user) throw new Error("邮箱或密码错误");

        // 2. 验证密码
        const isPasswordValid = await bcrypt.compare(
          credentials.password,
          user.password
        );
        if (!isPasswordValid) throw new Error("邮箱或密码错误");

        // 3. 获取当前登录的IP和设备信息
        const currentIp = getClientIp(req); // 从请求中获取IP
        const currentDevice = getDeviceInfo(req); // 获取设备信息（user-agent）
        const currentTime = new Date();

        // 4. 定义对比基准（首次登录用注册IP，非首次用上次登录IP）
        const isFirstLogin = !user.lastLogin; // 是否首次登录
        const lastLoginIp = user.lastLogin?.ipAddress || user.registerIp; // 上次IP
        const lastLoginDevice = user.lastLogin?.deviceInfo || "未知设备"; // 上次设备

        // 5. 检测IP和设备是否变更
        const isIpChanged = lastLoginIp && lastLoginIp !== currentIp;
        const isDeviceChanged = !currentDevice.includes(lastLoginDevice); // 简单匹配设备特征

        // 6. Debug日志：打印登录信息（方便调试）
        console.debug("[NextAuth登录检测]", {
          userId: user._id,
          email: user.email,
          isFirstLogin,
          currentIp,
          lastLoginIp,
          isIpChanged,
          currentDevice,
          lastLoginDevice,
          isDeviceChanged
        });

        // 7. 若IP/设备变更，发送通知邮件
        if (isFirstLogin || isIpChanged || isDeviceChanged) {
          // 异步发送邮件（不阻塞登录流程）
          sendLoginNotification(
            user.email,
            user.name,
            currentIp,
            currentDevice,
            currentTime,
            lastLoginIp || "无记录",
            lastLoginDevice
          ).catch(err => {
            console.error("[登录通知失败]", err);
          });
        }

        // 8. 更新用户登录记录（保存当前IP和设备）
        user.lastLogin = {
          ipAddress: currentIp,
          deviceInfo: currentDevice,
          timestamp: currentTime
        };

        // 9. 更新会话记录（保留最近5条）
        user.sessions = [
          ...user.sessions,
          {
            sessionId: uuidv4(), // 生成唯一会话ID
            ipAddress: currentIp,
            deviceInfo: currentDevice,
            createdAt: currentTime
          }
        ]
          .sort((a, b) => b.createdAt - a.createdAt) // 按时间倒序
          .slice(0, 5); // 保留最近5个会话

        await user.save({ validateBeforeSave: false }); // 保存更新

        // 10. 返回用户信息（NextAuth会生成token）
        return {
          id: user._id.toString(),
          name: user.name,
          email: user.email,
          userType: user.userType
        };
      }
    })
  ],
  session: {
    strategy: "jwt",
    maxAge: 30 * 24 * 60 * 60,
  },
  pages: {
    signIn: "/dashboard/login",
  },
  secret: process.env.NEXTAUTH_SECRET,
  callbacks: {
    async jwt({ token, user }) {
      if (user) {
        token.id = user.id;
        token.name = user.name;
        token.email = user.email;
        token.userType = user.userType;
      }
      console.log("nextauth时获取到的token:", token);
      return token;
    },
    async session({ session, token }) {
      if (session.user) {
        session.user.id = token.id;
        session.user.name = token.name;
        session.user.email = token.email;
        session.user.userType = token.userType;
      }
      console.log("nextauth时获取到的session:", session);
      return session;
    },
  },
};

const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };